package com.suray.rgv.son.comm;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import com.suray.basic.wcs.utils.comm.BaseMessageIf;
import com.suray.rgv.util.RgvLogger;
import com.suray.socket.SocketInterface;

import java.io.IOException;
import java.util.Arrays;

public class RgvSonComm {
    private SocketInterface socket;

    public RgvSonComm(SocketInterface socket) {
        this.socket = socket;
    }

    public synchronized byte[] comm(String des, BaseMessageIf message, int resendCount) throws IOException {
        try {
            socket.sendData(message.makeMessage());
            byte[] recData = socket.recData(2000);
            while (!checkData(recData)) {
                try {
                    byte[] resData = socket.recData(1000);
                    byte[] tempData = new byte[recData.length + resData.length];
                    System.arraycopy(recData, 0, tempData, 0, recData.length);
                    System.arraycopy(resData, 0, tempData, recData.length, resData.length);
                    recData = tempData;
                } catch (IOException e) {
                    RgvLogger.error(LoggerType.ERROR, null, null,
                            des + "接收到的数据不完整，通讯异常:" + Arrays.toString(recData), this.getClass());
                    throw e;
                }
            }
            RgvLogger.debug(LoggerType.COMM_DATA,null, des, " 返回数据:" + Arrays.toString(recData), this.getClass());

            return recData;
        } catch (IOException e) {
            if (resendCount > 0) {
                WcsFuncUtil.delay(1000);
                return comm(des, message, --resendCount);
            } else {
                throw e;
            }
        }
    }

    private boolean checkData(byte[] recData) throws IOException {
        if (recData.length < 3) {
            return false;
        }

        //功能码, 写功能码0x10, 读功能码0x04
        if (recData[1] == 0x4) {
            //写数据
            int size = recData[2] + 5;

            if (recData.length == size) {
                return true;
            } else if (recData.length < size) {
                return false;
            } else{
                throw new IOException("数据长度错误:" + Arrays.toString(recData));
            }
        } else if (recData[1] == 0x10) {
            //写数据
            if (recData.length == 8) {
                return true;
            }
        } else {
            throw new IOException("数据错误:" + Arrays.toString(recData));
        }

        return false;
    }

    private String changeData(byte[] data) {
        return new String(data);
    }

    public boolean isOnline() {
        return socket.isOnline();
    }

    public void close() {
        SocketInterface.deleteSocket(socket);
    }
}
